package service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import domain.Friend;
import domain.User;
import domain.example.FriendExample;
import service.IFriendService;
import service.IFriendTranService;
import service.IUserService;

@Service("FriendTranService")
public class FriendTranServiceImpl implements IFriendTranService {
	@Resource
	private IUserService userService;
	@Resource
	private IFriendService friendService;

	@Override
	public List<User> getFirendInfos(Integer userId) {
		List<User> result = new ArrayList<User>();
		
		if (userId == null) {
			return result; 
		}
		
		FriendExample example = new FriendExample();
		
		example.createCriteria().andRequestIdEqualTo(userId);
		example.or().andResponseIdEqualTo(userId);
		
		List<Friend> friends = friendService.selectByExample(example);
		
		if (friends == null) {
			return result;
		}
		
		for (Friend friend : friends) {
			int friendId = friend.getRequestId().compareTo(userId) == 0 ? friend.getResponseId() : friend.getRequestId();
			User fUser = userService.selectByPrimaryKey(friendId);
			User nUser = new User();
			nUser.setUserId(fUser.getUserId());
			nUser.setUserName(fUser.getUserName());
			result.add(nUser);
		}
		
		return result;
	}
	
	@Override
	public Friend getFriend(Integer userId, Integer anotherId) {
		if (userId == null || anotherId == null) {
			return null;
		}
		
		if (userId.compareTo(anotherId) > 0) {
			Integer t = userId;
			userId = anotherId;
			anotherId = t;
		}
		
		FriendExample example = new FriendExample();
		example.createCriteria().andRequestIdEqualTo(userId).andResponseIdEqualTo(anotherId);
	
		List<Friend> result = friendService.selectByExample(example);
		
		if (result == null || result.size() != 1) {
			return null;
		}
		
		return result.get(0);
	}

	@Override
	public boolean deleteFriend(Integer userId, Integer anotherId) {
		if (userId == null || anotherId == null) {
			return false;
		}
		
		if (userId.compareTo(anotherId) > 0) {
			Integer tid = userId;
			userId = anotherId;
			anotherId = tid;
		}
		
		FriendExample example = new FriendExample();
		example.createCriteria().andRequestIdEqualTo(userId).andResponseIdEqualTo(anotherId);
		
		int i = friendService.deleteByExample(example);
		
		return i == 1;
	}

}
